<template>
  <div class="login-container">
    <div class="login-form">
      <h2>图书管理系统</h2>
      <div class="form-group">
        <label>用户名</label>
        <input type="text" v-model="loginForm.username" placeholder="请输入用户名">
      </div>
      <div class="form-group">
        <label>密码</label>
        <input type="password" v-model="loginForm.password" placeholder="请输入密码">
      </div>
      <button class="btn btn-primary" @click="login" style="width:100%;padding:12px;">登录</button>
      <div v-if="loginError" style="color:var(--danger-color);margin-top:15px;text-align:center;">
        {{ loginError }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import AuthService from '@/services/auth';

export default {
  setup() {
    const store = useStore();
    const router = useRouter();
    const loginForm = ref({
      username: '',
      password: ''
    });
    const loginError = ref('');

    const login = async () => {
      if (!loginForm.value.username || !loginForm.value.password) {
        loginError.value = '请输入用户名和密码'
        return
      }

      try {
        const result = await AuthService.login(loginForm.value)
        if (result.success) {
          await store.dispatch('fetchCurrentUser')
          router.push('/dashboard')
        } else {
          loginError.value = result.message || '用户名或密码错误'
        }
      } catch (error) {
        console.error('登录失败:', error)
        loginError.value = '登录失败，请稍后再试'
      }
    };

    return {
      loginForm,
      loginError,
      login
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #3498db, #8e44ad);
}

.login-form {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  width: 100%;
  max-width: 400px;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: var(--dark-color);
}
</style>